import React, { useEffect, useState } from 'react';
import { Form, Input, message, AutoComplete, Table, Select, Button } from 'antd';
import ProForm, { ModalForm, ProFormText, ProFormDigit, ProFormRadio,ProFormTextArea,ProFormSelect } from '@ant-design/pro-form';
import {
  getGroupList,
  sendOthers,
  getlistSendOtherHistoryByPage
} from '../service'
import ProTable from '@ant-design/pro-table';
import { getStudentSearchOptions, selectStudent } from '@/global/service';
const { Option } = Select;
declare const ValidateStatuses: ['success', 'warning', 'error', 'validating', '', true];
declare type ValidateStatus = typeof ValidateStatuses[number];
interface SendFormProps {
  modalAddVisible: boolean;
  // uid: object;
  onCancel: () => void;
  onReload: () => void;
  id: number;
  courseId: number;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const TITLE_1 = '发送给其他学员'
const TITLE_2 = '发送历史'

const SendForm: React.FC<SendFormProps> = (props) => {
  const { modalAddVisible, onCancel, onReload ,id, courseId} = props;

  const [form] = Form.useForm();
  const [classOption,setClassOption] = useState<any>([]);
  const [title,setTitle] = useState(TITLE_1)
  const [batchValidStatus, setBatchValidStatus] = useState<any>('');
  const [batchErrorText, setBatchErrorText] = useState<string>('');
  const [curType,setCurType] = useState(0)
  const [options,setOptions] = useState([])
  const [uid,setUid] = useState()
  const [showHistory,setShowHistory] = useState(false)
  const [errorText,setErrorText] = useState('')
  const resetForm = () => {
    form.resetFields();
    // setClassOption([])
    setTitle(TITLE_1)

    setBatchValidStatus('')
    setBatchErrorText('')
    setErrorText('')

    setCurType(0)
    setUid('')
    setOptions([])
    setShowHistory(false)
    setClassOption([])

  }
  const onSelectUser = (data: any, option: any) => {
    setUid(option.id);
  };


  const onSearchUser = async (key: string) => {
    try {
      const data = await selectStudent({
        param:key,
        courseId
      });
      const options = getStudentSearchOptions(key, data);
      setOptions(options);
    } catch (error) {
      message.error('搜索失败');
    }
  };
  const close = () => {
    resetForm()
    onReload()
    onCancel()
  }
  const batchStatusHanlder = (status: ValidateStatus, text: string) => {
    setBatchValidStatus(status);
    setBatchErrorText(text);
  };
  const validPhoneListHandler = function (
    phones: string,
    statusHandler: (status: ValidateStatus, text: string) => void,
  ) {
    if (!phones) {
      statusHandler('error', '请输入发放的手机号');
      return false;
    }
    const arr = phones.split('\n');
    const lastStr = typeof Number(arr[arr.length - 1]);
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i] && isNaN(Number(arr[i]))) {
        statusHandler('error', '手机号仅可输入数字，请检查输入');
        return false;
      }
    }
    if (lastStr !== 'number' || isNaN(Number(arr[arr.length - 1]))) {
      statusHandler('error', '输入内容非数字结尾，请检查输入');
      return false;
    }

    const isValidLen = phones.split('\n');
    let unValidStr = '手机号格式不正确:';
    let hasUnValidPhone = false;
    for (let l = 0; l < isValidLen.length; l++) {
      if (
        isValidLen[l].length > 0 &&
        (isValidLen[l].length !== 11 || isValidLen[l].substr(0, 1) !== '1')
      ) {
        hasUnValidPhone = true;
        unValidStr += `${isValidLen[l]}，`;
      }
    }
    if (hasUnValidPhone) {
      statusHandler('error', unValidStr);
      return false;
    }
    return true;
  };
  const onFinish = async function () {
    const values = form.getFieldsValue();

    if(values?.sendType === 1 && !values.groupId){
      setErrorText('请选择班级')
      return
    }
    if ( values?.sendType === 0 ) {
      if( validPhoneListHandler(values.phones, batchStatusHanlder) === true){
        batchStatusHanlder(true, '');
      } else {
        return
      }
    }

    const res = await sendOthers({
      ...values,
      id,
    })
    if(res.code === 200){
      message.success('批量发送成功')
      close()
    } else {
      if (res.message.startsWith('500')) {
        batchStatusHanlder('error', res.message.replace('500', ''));
        return;
      }
      message.error(res.message);
    }
  };

  useEffect(() => {
    setTitle(showHistory ? TITLE_2 : TITLE_1)
    setErrorText('')
  },[showHistory])
  useEffect(() => {
    if(!modalAddVisible){
      return
    }
    getGroupList({
      courseId,
    }).then(res =>{
      const optionList =
      res.result.length === 0
        ? []
        : res.result.map((item: { id: any; name: any }) => {
            return { label: item.name, value: item.id };
          });
      setClassOption(optionList)
    })
  },[modalAddVisible])
  const columns = [
    {
      title: '用户昵称/手机号',
      dataIndex: 'key',
      hideInTable: true,
      order: 140,
      formItemProps: { labelCol: { span: 12 }},
      renderFormItem: () => (
        <AutoComplete
          options={options}
          onSelect={onSelectUser}
          onSearch={onSearchUser}
          placeholder="请选择"
          allowClear
          onClear={() => {
            setUid(null);
          }}
        />
      ),
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
      key: 'nickName',
      hideInSearch: true,
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      key: 'groupName',
      hideInSearch: true,
    },
    {
      title: '辅导老师',
      dataIndex: 'teacherName',
      key: 'teacherName',
      hideInSearch: true,
    },
    {
      title: '发送时间',
      dataIndex: 'sendTimeStr',
      key: 'sendTimeStr',
      hideInSearch: true,
    },
  ]
  return (
    <ModalForm
      title={title}
      visible={modalAddVisible}
      width="70%"
      modalProps={{
        onCancel: close,
        destroyOnClose: true,

      }}
      submitter={{
        render: () => [
          <Button key="1" onClick={close}>
            取消
          </Button>,
          (
            !showHistory ?
              <Button key="2" type="primary" onClick={onFinish}>
                发送
             </Button>:<></>
          ),
          (
            showHistory ?
              <Button key="3" onClick={()=>{
                setUid()
                setShowHistory(false)
                }} type="primary">
                返回发送至其他学员
              </Button> : <></>
          )
        ],
      }}
      form={form}
      {...formItemLayout}
      layout={'horizontal'}
    >
    {
      showHistory ?
      <ProTable<any>
        rowKey="key"
        onReset={()=>{
          setUid()
        }}
        request={async (params) => {
          const data = await getlistSendOtherHistoryByPage({
            reviewId: id,
            uid,
            pageNo: params.current,
            pageSize:20
          });
          return {
            data: data.result.records,
            success: true,
            total: data.result.total,
          };
        }}
          columns={columns}
      /> : <>
        <a style={{display: 'block',textAlign: 'right'}} onClick={()=>{setShowHistory(true)}}>发送历史</a>
     <ProFormRadio.Group
        name="sendType"
        label="选择用户"
        initialValue={0}
        required={true}
        fieldProps={{
          onChange:(e)=>{
            setCurType(e.target.value)
            setErrorText('')
            setBatchValidStatus('')
            setBatchErrorText('')
            form.setFieldsValue({
              phones:'',
              groupId:''
            })
          }
        }}
        options={[
          {
            label: '指定用户',
            value: 0,
          },
          {
            label: '指定班级',
            value: 1,
          },
          {
            label: '全班发送',
            value: 2,
          }
        ]}
      />
      {
        curType === 0 &&
        <ProFormTextArea
        name="phones"
        label="手机号"
        placeholder="手机手机号换行输入，每行1个手机号，最多支持500个用户同时发送号"
        help={batchErrorText}
        validateStatus={batchValidStatus}
        required={true}
        fieldProps={{
          showCount: {
            formatter: () => {
              if (!form.getFieldValue('phones')) {
                return `共0个用户`;
              }
              const list = form.getFieldValue('phones').split('\n');
              let listlen = 0;
              // 判断是否只是空格
              const reg = /^[ ]*$/;
              list.forEach((val: any) => {
                if (!reg.test(val)) {
                  listlen += 1;
                }
              });
              if (listlen > 500) {
                setBatchErrorText('单次做多支持500个用户发送');
                setBatchValidStatus('error');
              }

              return `共${listlen}个用户`;
            },
          },
        }}
      />
      }
      {
        curType === 1 &&
        <ProFormSelect
          name="groupId"
          label="选择班级"
          options={classOption}
          placeholder="请选择"
          rules={[{ required: true, message: '请选择班级' }]}
        />

      }
      <p style={{textAlign: 'right',color: 'red'}}>{errorText}</p>
      </>
    }
    </ModalForm>
  );
};

export default SendForm;
